package net.myspring.common.web;

import net.myspring.common.excel.ExcelBook;
import net.myspring.common.excel.ExcelUtils;
import net.myspring.common.utils.Encodes;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class ExcelView extends AbstractView {

    private Boolean office2003 = false;

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ExcelBook excelBook = (ExcelBook) model.get("excelBook");
        Workbook workbook = null;
        if (!office2003) {
            // 内存中保留 10000 条数据，以免内存溢出，其余写入 硬盘
            workbook = ExcelUtils.getWorkbook(new SXSSFWorkbook(10000), excelBook);
        } else {
            workbook = ExcelUtils.getWorkbook(new HSSFWorkbook(), excelBook);
        }
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode(excelBook.getName()));
        workbook.write(response.getOutputStream());
    }

    public Boolean getOffice2003() {
        return office2003;
    }

    public void setOffice2003(Boolean office2003) {
        this.office2003 = office2003;
    }
}
